﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Meraz.Core.Data;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Meraz.Core.Parsers;
using Meraz.Core.Managers;
using Meraz.Core.Helpers;
using Ninject;


namespace Meraz.Core.Commands
{
    public interface ICreateAliasesCommand
    {
        IAliasRepository AliasRepository { get; set; }
        Alias Execute(BlogKeyType blogKey, string aliasName);
        List<Alias> Execute(BlogKeyType blogKey, List<string> aliasNames);

    }
    public class CreateAliasesCommand : BaseCommand, ICreateAliasesCommand
    {
        [Inject]
        public CreateAliasesCommand(IAliasRepository AliasRepo)
        {
            this.AliasRepository = AliasRepo ?? new AliasRepository();
        }

        public IAliasRepository AliasRepository { get; set; }
        public Alias Execute(BlogKeyType blogKey, string aliasName){
            return Execute(blogKey, new List<string> {aliasName}).FirstOrDefault();
        }
        public List<Alias> Execute(BlogKeyType blogKey, List<string> aliasNames)
        {
            if (blogKey == BlogKeyType.Undefined || blogKey == BlogKeyType.Unknown)
                throw new ApplicationException();

            if (aliasNames == null || aliasNames.Count == 0)
                throw new ApplicationException();

            List<Alias> aliases = new List<Alias>();
            string blogName = blogKey.ToString();
            foreach (string aliasName in aliasNames)
            {
                Alias alias = AliasRepository.GetByName(blogName, aliasName);
                if (alias == null)
                {
                    alias = new Alias();
                    AliasRepository.Add(alias);
                    alias.BlogName = blogName;
                    alias.Name = aliasName;
                    alias.StatusType = StatusType.Undefined;
                }
                aliases.Add(alias);
            }
            Commit();
            return aliases;
        }
    }
}
